﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace IceDog.Lib.Event.Message
{
    public class Connection
    {
        public event EventHandler<MessageArrivedEventArgs> MessageArrived;
        private System.Timers.Timer pollTimer;
        private static Random random = new Random();
        public string Name { get; set; }
        public Connection()
        {
            pollTimer = new System.Timers.Timer(100);
            pollTimer.Elapsed += CheckForMessage;
        }
        public Connection(string name)
        {
            this.Name = name;
        }
        private void CheckForMessage(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine(this.Name+" check for new messages");
            //MessageArrived !=null表示此事件是否有订阅对象
            if ((random.Next(10)==0)&& MessageArrived !=null)
            {
                MessageArrived(this,new MessageArrivedEventArgs("message arrived:" + e.SignalTime.ToString()));
            }
        }

        public void Connect()
        {
            pollTimer.Enabled = true;
            pollTimer.Start();
        }
        public void DisConnect()
        {
            pollTimer.Enabled = false;
            pollTimer.Stop();
        }
    }
}
